package com.you.atlas.web.member.module.action;

import static com.you.atlas.web.member.constant.AuthConstant.LOGIN_ID;
import static com.you.atlas.web.member.constant.AuthConstant.PASSWORD;

import javax.annotation.Resource;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.you.atlas.web.member.constant.AuthConstant;
import com.you.atlas.web.member.constant.AuthFailure;
import com.you.atlas.web.member.sectury.AuthCallBack;
import com.you.atlas.web.member.sectury.Authenticator;
import com.you.common.webx.AuthContext;

public class LoginAction implements AuthCallBack {

    @Resource(name = "loginIdPasswordAuthenticator")
    private Authenticator loginIdPasswordAuthenticator;

    public void doLogin(@FormGroup("login") Group group, TurbineRunData rundata, Navigator navigator) {

        String loginId = group.getField("loginId").getValue().toString();
        String password = group.getField("password").getValue().toString();
        doLogin(loginId, password, rundata, navigator);

    }

    protected void doLogin(String loginId, String password, TurbineRunData rundata, Navigator navigator) {
        rundata.getRequest().setAttribute(LOGIN_ID, loginId);
        rundata.getRequest().setAttribute(PASSWORD, password);
        loginIdPasswordAuthenticator.auth(rundata, navigator, this);
    }

    @Override
    public void failure(TurbineRunData rundata, Navigator navigator) {
        AuthFailure authFailure = (AuthFailure) rundata.getRequest().getAttribute(AuthConstant.AUTH_FAILURE);
        rundata.getRequest().setAttribute("error", authFailure);
    }

    @Override
    public void success(TurbineRunData rundata, Navigator navigator) {
        String done = rundata.getRequest().getParameter("done");
        if (done != null) {
            navigator.redirectToLocation(done);
        } else {
            navigator.redirectTo("memberModule").withTarget("me.vm");
        }

    }
}
